﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FairyGUI;
using System;

public class FRoomPanelMediator : MyWindow {
    GTextInput _modelInput;
    GTextInput _widthInputField;
    GTextInput _heightInputField;
    GButton _themeTrigger;
    GComboBox _themeBox;
    GButton _BGMTrigger;
    GComboBox _BGMBox;
    GList _editorList;
    GGraph _mapGraph;
    GList _gridList;
    List<GMConfig.RoomArrange> _roomArrangeList;
    List<FixedRoom> _fixedRoomList;
    FixedRoom fixedRoom;
    RenderWindowMediator renderWindow;
    int preIndex = -1;
    int _widht;
    int _height;
    List<PackageItem> _assets;
    GComponent _toolbar;
    FFixedRoomListPopup fixedRoomListPopup;
    GButton removeBtn;
    int removeIndex;
	public FRoomPanelMediator(){
        _roomArrangeList = new List<GMConfig.RoomArrange>();
		this.contentPane = UIPackage.CreateObject("MapPackages", "RoomEditor").asCom;

        _toolbar = contentPane.GetChild("toolbar").asCom;
        _modelInput = _toolbar.GetChild("modelInput").asCom.GetChild("input").asTextInput;
        _widthInputField = _toolbar.GetChild("widthInputField").asCom.GetChild("input").asTextInput;
        _heightInputField = _toolbar.GetChild("heightInputField").asCom.GetChild("input").asTextInput;
        
        _themeTrigger = _toolbar.GetChild("ThemeTrigger").asButton;
        _themeBox = _toolbar.GetChild("ThemeBox").asComboBox;
        _BGMTrigger = _toolbar.GetChild("BGMTrigger").asButton;
        _BGMBox = _toolbar.GetChild("BGMBox").asComboBox;
        _editorList = _toolbar.GetChild("EditorList").asList;
        removeBtn = contentPane.GetChild("removeBtn").asButton;

        _themeBox.onChanged.Add(() => {
            fixedRoom.SetBox(_themeBox.title,null);
        });

        _BGMBox.onChanged.Add(() =>
        {
            int index = _BGMBox.selectedIndex;
            fixedRoom.SetBox(null,_assets[index].name);
        });

        _themeTrigger.onClick.Add(() => {
            if (_themeTrigger.GetController("button").selectedIndex != 3)
                fixedRoom.SetBox("",null);
        });

        _BGMTrigger.onClick.Add(() =>
        {
            if (_BGMTrigger.GetController("button").selectedIndex != 3)
                fixedRoom.SetBox(null, "");
        });

        _assets = MyUIPackage.GetAllPointAssets("AudioPackage", PackageItemType.Sound);
        string[] items = new string[_assets.Count];
        for (int i = 0; i < _assets.Count; i++)
        {
            items[i] = _assets[i].name;
        }
        _BGMBox.items = items;

        _toolbar.GetChild("ReadRoomBtn").asButton.onClick.Add(OpenRoomList);

        _toolbar.GetChild("CreateRoomBtn").asButton.onClick.Add(() =>
        {
            _widthInputField.text = "10";
            _heightInputField.text = "10";
            _modelInput.text = "默认";
            onRectInputChanged();
        });

        renderWindow = new RenderWindowMediator();
        _toolbar.GetChild("PreviewBtn").asButton.onClick.Add(() => {
            // _toolbar.GetChild("SaveBtn").asButton.FireClick(false);
            fixedRoom.roomArrangeList = _roomArrangeList;
            fixedRoom.name = _modelInput.text;
            renderWindow.Show();
            renderWindow.InitData(fixedRoom);
        });

        _toolbar.GetChild("SaveBtn").asButton.onClick.Add(() => {
            LoadJSON();
            if (string.IsNullOrEmpty(_modelInput.text)){
                FUIMain.TipPanel("请输入模板名！");
                return;
            }
            if (string.IsNullOrEmpty(_widthInputField.text) || string.IsNullOrEmpty(_heightInputField.text))
            {
                FUIMain.TipPanel("请输入大小！");
                return;
            }

            fixedRoom.roomArrangeList = _roomArrangeList;
            fixedRoom.name = _modelInput.text;

            if (!fixedRoom.IsCompleteSet()){
                FUIMain.TipPanel("请完成未设置条目后再次保存！");
                return;
            }
            
            bool replaced = false;
            for (int i = 0; i < _fixedRoomList.Count; i++)
            {
                if (_fixedRoomList[i].name == fixedRoom.name) {
                    _fixedRoomList[i] = fixedRoom.DeepClone();
                    replaced = true;
                }
            }
            
            if(!replaced) {
                _fixedRoomList.Add(fixedRoom.DeepClone());
            }

            if (replaced)
            {
                FUIMain.TipPanel(string.Format("是否覆盖{0}项？", fixedRoom.name), (result) =>
                {
                    if ((int)result == 1)
                    {
                        Utils.SaveByJson<List<FixedRoom>>(Application.dataPath, "fixedRoomList.json", _fixedRoomList);
                        FUIMain.TipPanel("保存成功！");
                    }
                });
            }else{
                Utils.SaveByJson<List<FixedRoom>>(Application.dataPath, "fixedRoomList.json", _fixedRoomList);
                FUIMain.TipPanel("保存成功！");
            }
        }); 

        _gridList = contentPane.GetChild("gridList").asList;

        _gridList.onRightClickItem.Add((EventContext context) => {
            GButton item = context.data as GButton;
            int index = _gridList.GetChildIndex(item);
            
            if (_roomArrangeList[index] == GMConfig.RoomArrange.None || 
                _roomArrangeList[index] == GMConfig.RoomArrange.Wall) return;
            removeIndex = index;
            removeBtn.visible = true;
            Vector2 pos = new Vector2(item.xy.x + _gridList.xy.x,item.xy.y + _gridList.xy.y);
            removeBtn.xy = pos;
        });
        contentPane.onClick.Add((EventContext context) => {
            removeBtn.visible = false;
        });

        contentPane.GetChild("removeBtn").onClick.Add(() => {
            FUIMain.TipPanel("确定删除此元素？",(object state) => {
                if ((int)state == 1) {
                    _gridList.GetChildAt(removeIndex).icon = "";
                    _gridList.GetChildAt(removeIndex).asButton.title = "";
                    fixedRoom.idList[removeIndex] = -1;
                    if (removeIndex >= fixedRoom.width) 
                        _roomArrangeList[removeIndex] = GMConfig.RoomArrange.None;
                    else
                        _roomArrangeList[removeIndex] = GMConfig.RoomArrange.Wall;
                    ReFreshPreview();
                }
            });
        });

        _gridList.onClickItem.Add((EventContext context) => {
            GButton item = context.data as GButton;
            int itemIndex = _gridList.GetChildIndex(item);
            GMConfig.RoomArrange arrange = _roomArrangeList[itemIndex];
            System.IO.FileInfo[] blocks = null;
            GMConfig.ProductType productType = GMConfig.ProductType.None;
            bool isExecute;
            switch (arrange)
            {
                case GMConfig.RoomArrange.Item:
                    isExecute = false;
                    FItemListMediator itemListMediator = FUIMain.ShowPanel(GMConfig.PanelType.ItemList) as FItemListMediator;
                    itemListMediator.loadItem = (int index) =>
                    {
                        List<Item> _dataList = ItemManager.Instance._itemList;
                        Item data = _dataList[index];
                        fixedRoom.idList[itemIndex] = data.id;
                        item.title = data.id.ToString();
                    };
                    break;
                case GMConfig.RoomArrange.Block:
                    blocks = Utils.GetFiles(Application.dataPath + "/Resources/Map/Blocks", "*.prefab");
                    isExecute = true;
                    productType = GMConfig.ProductType.MonsterRoom;
                    break;
                case GMConfig.RoomArrange.Boss:
                    isExecute = true;
                    productType = GMConfig.ProductType.Boss;
                    break;
                case GMConfig.RoomArrange.Elite:
                    isExecute = true;
                    productType = GMConfig.ProductType.Elite;
                    break;
                case GMConfig.RoomArrange.Retinue:
                    isExecute = true;
                    productType = GMConfig.ProductType.Monster;
                    break;
                default:
                    isExecute = false;
                    break;
                
            }
            if (isExecute){
                FCommonListMediator commonListPanel = FUIMain.ShowPanel(GMConfig.PanelType.CommonListPanel) as FCommonListMediator;
                commonListPanel.SetRenderer(productType, null, blocks);
                commonListPanel.loadData = (int index) =>
                {
                    List<Item> _dataList = ItemManager.Instance._itemList;
                    Item data = _dataList[index];
                    fixedRoom.idList[itemIndex] = data.id;
                    item.title = data.id.ToString();
                };
            }
        });

        _widthInputField.onChanged.Add(onRectInputChanged);
        _heightInputField.onChanged.Add(onRectInputChanged);
        _modelInput.onChanged.Add(() => {

        });

        AddEventListener();
        LoadJSON();
        fixedRoom = new FixedRoom();
    }
    void LoadCommonListPanel(GMConfig.ProductType productType)
    {
        FCommonListMediator commonListPanel = FUIMain.ShowPanel(GMConfig.PanelType.CommonListPanel) as FCommonListMediator;
        // commonListPanel.SetWithProduct(productType, _lists, _map, fixedRoomList, blocks);
    }
    void OpenRoomList(){
        fixedRoomListPopup = FUIMain.ShowPanel(GMConfig.PanelType.SelectRoomListPopup, (status) => { }) as FFixedRoomListPopup;
        fixedRoomListPopup.loadRoom = LoadFixedRoom;
    }

    void LoadJSON(){
        _fixedRoomList = Utils.LoadByJson<List<FixedRoom>>(Application.dataPath, "fixedRoomList.json");
        if (_fixedRoomList == null) _fixedRoomList = new List<FixedRoom>();
    }

    protected override void OnInit()
    {
        base.OnInit();
        this.Center();
        
    }
    protected override void OnShown(){
        base.OnShown();
        //默认打开读取房间列表
        OpenRoomList();
    }
    protected override void OnHide(){
        base.OnHide();
        if (fixedRoomListPopup != null)
            fixedRoomListPopup.HideImmediately();
        if (renderWindow != null)
            renderWindow.HideImmediately();
    }
    //读取房间
    public void LoadFixedRoom(int index){
        if (_fixedRoomList.Count == 0) return;
        if (preIndex == index) return;
        
        preIndex = index;
        fixedRoom = _fixedRoomList[index];

        GenerateGrids(fixedRoom.width, fixedRoom.height,false);
        _gridList.numItems = fixedRoom.width * fixedRoom.height;
        _roomArrangeList = fixedRoom.roomArrangeList;

        for (int i = 0; i < _gridList.numItems; i++){
            GButton item = _gridList.GetChildAt(i).asButton;
            item.title = "";
            AddGridDragDrop(item);
            if ((int)fixedRoom.roomArrangeList[i] > (int)GMConfig.RoomArrange.None && (int)fixedRoom.roomArrangeList[i] < (int)GMConfig.RoomArrange.Wall){
                item.icon = _editorList.GetChildAt((int)fixedRoom.roomArrangeList[i] - 1).asButton.icon;
                if((int)fixedRoom.roomArrangeList[i] < (int)GMConfig.RoomArrange.Born)
                    item.title = fixedRoom.idList[i] == -1 ? "未" : fixedRoom.idList[i].ToString();
            }
            //第一行： 墙
            if (i < fixedRoom.width)
                item.GetChild("grid").asGraph.color = new Color(0, 0, 0, 1);
        }

        _modelInput.text = fixedRoom.name;
        _widthInputField.text = fixedRoom.width.ToString();
        _heightInputField.text = fixedRoom.height.ToString();
        _widht = fixedRoom.width;
        _height = fixedRoom.height;

        _themeBox.title = fixedRoom.theme;
        _BGMBox.title = fixedRoom.bgm;

        if (renderWindow.enabled) {
            renderWindow.InitData(fixedRoom);
        }

    }

    void onRectInputChanged(){
        if (string.IsNullOrEmpty(_widthInputField.text) || string.IsNullOrEmpty(_heightInputField.text)) return;
        _widht = int.Parse(_widthInputField.text);
        _height = int.Parse(_heightInputField.text) + 1;

        GenerateGrids(_widht,_height);

        for (int i = 0; i < _gridList.numItems; i++)
        {
            //监听拖拽释放事件
            GButton item = _gridList.GetChildAt(i).asButton;
            AddGridDragDrop(item);

            //第一行： 墙
            if (i < _widht) {
                item.GetChild("grid").asGraph.color = new Color(0,0,0,1);
                _roomArrangeList[i] = GMConfig.RoomArrange.Wall;
            }
        }
    }

    //监听表格拖拽事件
    void AddGridDragDrop(GButton item){
        item.icon = null;
        item.GetChild("grid").asGraph.color = new Color(1, 1, 1, 1);
        item.onDrop.Add((EventContext context) =>
        {
            Data data = (Data)context.data;
            GMConfig.RoomArrange arrange = (GMConfig.RoomArrange)Enum.Parse(typeof(GMConfig.RoomArrange), data.index.ToString());
            int index = _gridList.GetChildIndex(item);
            if (_roomArrangeList[index] == GMConfig.RoomArrange.Wall && arrange != GMConfig.RoomArrange.Light) {
                return;
            }

            item.icon = data.icon;
            if (data.isGrid) {
                _gridList.GetChildAt(data.origin).icon = "";
                _gridList.GetChildAt(data.origin).asButton.title = "";
                fixedRoom.idList[data.origin] = -1;
                //墙
                if (data.origin < _widht)
                    _roomArrangeList[data.origin] = GMConfig.RoomArrange.Wall;
                else
                    _roomArrangeList[data.origin] = GMConfig.RoomArrange.None;
            }
            _roomArrangeList[index] = arrange;
            fixedRoom.idList[index] = data.id;

            if ((int)_roomArrangeList[index] > (int)GMConfig.RoomArrange.None && (int)_roomArrangeList[index] < (int)GMConfig.RoomArrange.Born)
                item.title = fixedRoom.idList[index] == -1 ? "未" : fixedRoom.idList[index].ToString();
            else 
                item.title = "";
            ReFreshPreview();
        });
        //监听移动位置事件
        item.draggable = true;
        item.onDragStart.Add((EventContext context) =>
        {
            Data data = new Data();
            data.icon = item.icon;
            int index = _gridList.GetChildIndex(item);
            data.index = (int)_roomArrangeList[index];
            data.isGrid = true;
            data.origin = index;
            data.id = fixedRoom.idList[index];

            context.PreventDefault();
            // item.icon = "";

            if (!string.IsNullOrEmpty(item.icon))
                DragDropManager.inst.StartDrag(item.GetChild("icon").asGraph, data.icon, data, (int)context.data);
            else {
                _gridList.StartDrag((int)context.data);
            }
        });
        // item.onDragEnd.Add((EventContext context) =>
        // {
        //     item.icon = "";
        //     Debug.Log(context.ToString() + "-----------");

        // });
        DragDropManager.inst.dragAgent.onDragEnd.Add((EventContext context) => {
            Debug.Log(context.data + "-----------");

        });
    }

    void ReFreshPreview(){
        fixedRoom.roomArrangeList = _roomArrangeList;
        //拖拽后刷新预览房间
        if (renderWindow.visible)
        {
            renderWindow.InitData(fixedRoom);
        }
    }

    void GenerateGrids(int width, int height, bool isClear = true){
        fixedRoom.width = width;
        fixedRoom.height = height;

        int gridCount = width * height;
        _gridList.Center();
        _gridList.numItems = gridCount;
        _gridList.width = width * 20;
        _gridList.height = height * 20;

        if(isClear) {
            _roomArrangeList.Clear();
            for (int i = 0; i < gridCount; i++)
            {
                _roomArrangeList.Add(GMConfig.RoomArrange.None);
                
            }
        }
    }

    void AddEventListener(){
        for (int i = 0; i < _editorList.numItems; i++)
        {
            GButton item = _editorList.GetChildAt(i).asButton;
            item.draggable = true;
            item.onDragStart.Add((EventContext context) => {
                Data data = new Data();
                data.icon  = item.icon;
                data.index = _editorList.GetChildIndex(item) + 1;

                context.PreventDefault();
                DragDropManager.inst.StartDrag(item, item.icon, data, (int)context.data);
            });
        }
    }

}
  
struct Data
{
    public string icon;
    public int index;
    public bool isGrid;
    public int origin;
    public int id;
}